/*
 * Copyright © 2009 Gerald Isaac Schwarz
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package base;

import java.util.ArrayList;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Color;
import java.io.File;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import org.xml.sax.SAXException;

public class GameLoader {
	private File file;
	private Document document;
	private ArrayList<Player> players = new ArrayList<Player>();
	private ArrayList<Piece> pieces = new ArrayList<Piece>();
	private Engine engine;
	private Player currentPlayer;
	private Board board;
	
//	TODO Stop using InputStream.
	
	public GameLoader(InputStream inputStream) {
		try {
			this.getDocument(inputStream);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try {
			this.loadGame();
		} catch (DOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public GameLoader(File file) {
		this.file = file;
		
		if (!this.file.exists()) {
			throw new RuntimeException("Specified file doesn't exist.");
		}
		else if (this.file.isDirectory()) {
			throw new RuntimeException("Specified file is a directory.");
		}
		
		try {
			this.getDocument();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try {
			this.loadGame();
		} catch (DOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
//	TODO Stop using InputStream.
	
	private void getDocument(InputStream inputStream) throws IOException, SAXException, ParserConfigurationException {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		dbf.setValidating(true);
//		dbf.setNamespaceAware(true);
		dbf.setIgnoringElementContentWhitespace(true);
		this.document = dbf.newDocumentBuilder().parse(inputStream);
		this.document.getDocumentElement().normalize();
	}
	
	private void getDocument() throws IOException, SAXException, ParserConfigurationException {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		dbf.setValidating(true);
//		dbf.setNamespaceAware(true);
		dbf.setIgnoringElementContentWhitespace(true);
		this.document = dbf.newDocumentBuilder().parse(file);
		this.document.getDocumentElement().normalize();
	}
	
	private void loadPlayers() {
		NodeList players = this.document.getElementsByTagName("player");
		
		for (int i = 0; i < players.getLength(); i++) {
			String name = this.getTextContent(players.item(i).getAttributes().getNamedItem("name"));
			Integer id = Integer.parseInt(this.getTextContent(players.item(i).getAttributes().getNamedItem("id")));
			Color color = new Color(Integer.parseInt(this.getTextContent(players.item(i).getAttributes().getNamedItem("color"))));
			
			this.players.add(new base.Player(name, id, color));
		}
	}
	
	private void loadCurrentPlayer() {
		int id = Integer.parseInt(this.getTextContent(this.document.getElementsByTagName("current_player").item(0)));
		
		this.currentPlayer = this.getPlayerById(id);
	}
	
	private void loadBoard() {
		Node boardNode = this.document.getElementsByTagName("board").item(0);
		
		int boardWidth = Integer.parseInt(this.getTextContent(boardNode.getAttributes().getNamedItem("width")));
		int boardHeight = Integer.parseInt(this.getTextContent(boardNode.getAttributes().getNamedItem("height")));
		
		NodeList pieceNodes = ((Element) boardNode).getElementsByTagName("piece");
		
		for (int h = 0; h < pieceNodes.getLength(); h++) {
			Integer level = Integer.parseInt(this.getTextContent(pieceNodes.item(h).getAttributes().getNamedItem("level")));
			Integer id = Integer.parseInt(this.getTextContent(pieceNodes.item(h).getAttributes().getNamedItem("owner")));
			int x = Integer.parseInt(this.getTextContent(pieceNodes.item(h).getAttributes().getNamedItem("x")));
			int y = Integer.parseInt(this.getTextContent(pieceNodes.item(h).getAttributes().getNamedItem("y")));
			
			Player player = this.getPlayerById(id);
			Piece piece = new Piece(new Point(x, y), level, player);
			
			this.pieces.add(piece);
		}
		
		this.board = new Board(this.currentPlayer, new Dimension(boardWidth, boardHeight), this.pieces);
	}
	
	private void loadEngine() throws InstantiationException, IllegalAccessException, ClassNotFoundException {
		this.engine = new Engine(this.board);
	}
	
	private void loadGame() throws DOMException, InstantiationException, IllegalAccessException, ClassNotFoundException {
		this.loadPlayers();
		this.loadCurrentPlayer();
		this.loadBoard();
		this.loadEngine();
	}
	
	private Player getPlayerById(int id) {
		for (Player player : this.players) {
			if (player.getId() == id) {
				return player;
			}
		}
		
		return null;
	}
	
	private String getTextContent(Node node) {
		return node.getTextContent().trim();
	}

	public Engine getEngine() {
		return this.engine;
	}
}